package com.yyfax.pay.console.service.impl;

import javax.annotation.Resource;

import com.yyfax.pay.common.exception.PayExceptionCode;
import com.yyfax.pay.console.vo.OrderInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yyfax.framework.common.Log;
import com.yyfax.pay.common.annotation.BusiType;
import com.yyfax.pay.common.enums.*;
import com.yyfax.pay.console.domain.ExceptionRecordDO;
import com.yyfax.pay.console.service.CommonExceptionService;
import com.yyfax.pay.console.vo.DealResultVO;
import com.yyfax.pay.depository.dao.FuiouChargeDao;
import com.yyfax.pay.depository.dao.FuiouNotifyTaskDao;
import com.yyfax.pay.depository.domain.FuiouCharge;
import com.yyfax.pay.depository.domain.FuiouNotifyTask;

import java.util.ArrayList;

@Service
@BusiType(BusiTypeEnum.ENTRUST_CHARGE)
public class EntrustChargeExpHandler extends CommonExceptionService {

	@Resource
	private FuiouChargeDao fuiouChargeDao;

	@Resource
	private FuiouNotifyTaskDao fuiouNotifyTaskDao;

	Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public DealResultVO dealException(String busiId, BusiTypeEnum busiTypeEnum, Integer expType) {
		final String OP = "EntrustChargeExpHandler.handle";
		try {
			FuiouCharge fuiouCharge = fuiouChargeDao.selectByBusiId(busiId);
			if (null == fuiouCharge ) {
				logger.warn(Log.op(OP).msg("查询到异常记录订单不存在,不做操作").kv("busiId", busiId).kv("expType", expType).toString());
				return new DealResultVO(ExpRecordStateEnum.RESOLVED_FAIL.getValue(),ExpRecordStateEnum.RESOLVED_FAIL.getDesc());
			}

			//暂停异步通知任务
			pauseNotify(busiId, expType);

			// 更新订单状态为已受理,更新异步通知状态为未通知
            fuiouChargeDao.updateStateAndNotify(busiId, OrderStateEnum.ACCEPTED.getValue(), null, null,
                        NotifyStateEnum.NOT_NOTIFY.getValue());
			logger.info(Log.op(OP).msg("更新订单状态成功").kv("originState", fuiouCharge.getState()).toString());
        } catch (Exception e) {
            logger.error(Log.op(OP).msg("后台更新委托充值订单状态异常").kv("busiId", busiId).toString());
            return new DealResultVO(ExpRecordStateEnum.RESOLVED_FAIL.getValue(),ExpRecordStateEnum.RESOLVED_FAIL.getDesc());
        }
        return new DealResultVO(ExpRecordStateEnum.RESOLVED_SUCCESS.getValue(),ExpRecordStateEnum.RESOLVED_SUCCESS.getDesc());
    }

	@Override
	public OrderInfoVO queryOrderInfo(String busiId) {
		final String OP = "EntrustChargeExpHandler.queryOrderInfo";
		FuiouCharge fuiouCharge = fuiouChargeDao.selectByBusiId(busiId);
		if (null == fuiouCharge) {
			logger.warn(Log.op(OP).msg("查询到原支付订单不存在").kv("busiId", busiId).toString());
			throw PayExceptionCode.ORDER_NOT_FOUND.exp();
		}
		return new OrderInfoVO(fuiouCharge.getUserId(),fuiouCharge.getAmount());
	}

	private void pauseNotify(String busiId, Integer expType) {
		final String OP = "EntrustChargeExpHandler.pauseNotify";
		// 停止异步通知任务
		FuiouNotifyTask fuiouNotifyTask = fuiouNotifyTaskDao.queryByUniqueKey(busiId, FuiouBusiTypeEnum.ENTRUST_CHARGE.getValue());
		if (null != fuiouNotifyTask && (TaskStateEnum.ACTIVE.getValue().equals(fuiouNotifyTask.getState())|| TaskStateEnum.DEALING.getValue().equals(fuiouNotifyTask.getState()))) {
			logger.info(Log.op(OP).msg("存在异步通知任务,停掉异步通知任务").kv("fuiouNotifyTask", fuiouNotifyTask).toString());
		    int uCount = fuiouNotifyTaskDao.updateStateByUniqueKey(busiId, FuiouBusiTypeEnum.ENTRUST_CHARGE.getValue(), TaskStateEnum.FAILED.getValue());
		    if (uCount != 1) {
		        logger.error(Log.op(OP).msg("取消异步通知异常").kv("fuiouNotifyTask", fuiouNotifyTask).kv("busiId", busiId).kv("expType", expType).toString());
            }
		}
	}
}
